package stack;

import java.util.Iterator;

public class Stack<T> implements Iterable<T> {
    private Node head;
    private int N;
    public boolean isEmpty(){
        return N==0;
    }
    //获取栈中的元素
    public int size(){
        return N;
    }
    public Stack(){
        head = new Node(null,null);
        N = 0;
    }

    //增加元素
    public void push(T t){
       Node oldLast = head.next;
        Node newNode = new Node(t, oldLast);
        head.next = newNode;
        N++;
    }
    //删除元素
    public T pop(){
       Node oldNode = head.next;
       if (oldNode ==null){
           return null;
       }
       Node nextNode = head.next.next;
       head.next = nextNode;
       N--;
       return oldNode.item;

    }

    @Override
    public Iterator<T> iterator() {
        return new iMiter();
    }
    public class iMiter implements Iterator{
        private Node n;

        public iMiter() {
            this.n = head;
        }

        @Override
        public boolean hasNext() {
            return n.next != null;
        }

        @Override
        public Object next() {
            n=n.next;
            return n.item;
        }
    }

    //节点类
    private class Node{
        T item;
        Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }
}
